﻿//------------------------------------------------------------------------------
// <copyright file="INotifyPropertyChangedExtensions.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;

namespace DAnton.Utilities.Extensions
{
public static class INotifyPropertyChangedExtension
{
    public static void OnPropertyChanged(this INotifyPropertyChanged sender, string propertyName)
    {
        Type type = sender.GetType();

        while (type != null)
        {
            FieldInfo eventFieldInfo = type.GetField("PropertyChanged", 
                                                        BindingFlags.Public | 
                                                        BindingFlags.NonPublic | 
                                                        BindingFlags.FlattenHierarchy | 
                                                        BindingFlags.Instance);

            if (eventFieldInfo != null)
            {
                MulticastDelegate eventDelegate = eventFieldInfo.GetValue(sender) as MulticastDelegate;

                if (eventDelegate != null)
                {
                    eventDelegate.DynamicInvoke(new object[] { sender, new PropertyChangedEventArgs(propertyName) });
                    break;
                }
            }

            type = type.BaseType;
        }
    }
}
}
